package com.example.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.app.entity.Consumer;
import com.example.app.service.IConsumerService;
import com.example.common.config.ConfigProperties;
import com.example.common.config.TransWrapper;
import com.example.common.constant.SystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private IConsumerService consumerService;
    @Autowired
    private ConfigProperties configProperties;

    @GetMapping("/login/cellphone")
    public Map<String, Object> login(HttpServletRequest request){

        String phone = request.getParameter("phone");

        String password = request.getParameter("password");

        QueryWrapper<Consumer> wrapper = new QueryWrapper<>();

        wrapper.eq("phone_num", phone);

        wrapper.eq("password", password);

        Consumer one = consumerService.getOne(wrapper);

        Map<String, Object> profile = TransWrapper.wrap("profile", one);

        if(one != null){
            one.setAvatarUrl(configProperties.getNginxBasePath() + one.getAvator());
            one.setUserId(one.getId());
            one.setNickname(one.getUsername());
            HttpSession session = request.getSession();
            session.setAttribute(SystemConstant.CURRENT_USER, one);
            profile.put("code", 200);
        }else{
            profile.put("code", 500);
        }
        return profile;
    }


}
